package cy.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ModelDriven;

import cy.pageModel.Json;
import cy.pageModel.User;
import cy.service.UserServiceI;

@ParentPackage("basePackage")
@Namespace("/")
@Action(value = "userAction")
public class UserAction extends BaseAction implements ModelDriven<User> {

    private User user = new User();

    @Override
    public User getModel() {
        return user;
    }

    private UserServiceI userService;

    public UserServiceI getUserService() {
        return userService;
    }

    @Autowired
    public void setUserService(UserServiceI userService) {
        this.userService = userService;
    }

    public void reg() {
        Json json = new Json();
        try {
            User u = userService.save(user);
            json.setSuccess(true);
            json.setMsg("注册成功!");
            json.setObj(u);

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("注册失败!");
        }
        super.writeJson(json);

    }

    public void login() {
        Json json = new Json();
        User u = userService.find(user);
        String realCode = (String) session.get("code");
        if (user.getCode() != null && user.getCode().equalsIgnoreCase(realCode)) {
            if (u != null) {
                json.setSuccess(true);
                json.setMsg("登陆成功!");
            } else {
                json.setMsg("登陆失败,用户名或密码错误!");
            }
        } else {
            json.setMsg("验证输入错误!");
        }

        super.writeJson(json);

    }

    public void dataGrid() {
        super.writeJson(userService.dataGrid(user));
    }

    public void remove() {
        userService.delete(user);
        Json json = new Json();
        json.setSuccess(true);
        json.setMsg("删除成功!");
        super.writeJson(json);
    }

    public void edit() {
        User u = userService.edit(user);
        Json json = new Json();
        json.setSuccess(true);
        json.setMsg("编辑成功!");
        json.setObj(u);
        super.writeJson(json);
    }
}
